from paddleocr import PaddleOCR, draw_ocr
import os

os.environ['KMP_DUPLICATE_LIB_OK'] = 'TRUE'

# ocr包安装
# pip install paddleocr
# pip install paddlepaddle
# 出现错误：OMP: Error #15: Initializing libiomp5md.dll, but found libiomp5md.dll already initialized.
# 打开 import os
# os.environ['KMP_DUPLICATE_LIB_OK'] = 'TRUE'


class ImageScoreOcrPaddle:
    _instance = None
    _ocr = None

    def __init__(self):
        if self._instance is not None:
            return
        # 生成paddleocr类
        if self._ocr == None:
            self._ocr = PaddleOCR(use_angle_cls=True, lang='ch')  # 启用角度分类器并使用中文模型

    def __new__(cls):
        # print("__new__")
        if cls._instance is None:
            instance = super().__new__(cls)
            instance.__init__()  # 如果需要初始化操作
            cls._instance = instance
        return cls._instance

    def __parse_ocr(self, ocr_result):
        try:
            results = []
            for idx, res in enumerate(ocr_result):
                # print(f"Text block {idx + 1}:")
                for line in res:
                    text = line[1][0]  # 获取识别的文本
                    confidence = line[1][1]  # 获取识别的置信度
                    results.append({"text": text, "confidence": confidence})
                    # print(f"  - Detected text: {text}, Confidence: {confidence:.2f}")
            return results
        except Exception as e:
            print(f"解析图片中OCR提取文字出错: {e}")
            return None

    def get_ocr(self, path_img):
        # ocr
        ocr_result = self._ocr.ocr(path_img)
        # 解析ocr结果
        results = self.__parse_ocr(ocr_result)
        return results


if __name__=="__main__":
    image_ocr = ImageScoreOcrPaddle()
    path_img_list = ['../files/ans/ans_4_2.png',
                     '../files/ans/ans_5_1.png',
                     '../files/ans/ans_5_3.png',
                     '../files/ans/ans_5_5.png']
    results_list = []
    for path_img in path_img_list:
        results = image_ocr.get_ocr(path_img)
        if results is not None:
            results_list.append(results)
    for i in range(len(results_list)):
        results = results_list[i]
        print(path_img_list[i])
        print(results)